package com.foodcommunity.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class FileUploadUtil {
    private static String uploadPath;

    @Value("${upload.path}")
    public void setUploadPath(String path) {
        uploadPath = path + "/images/";
    }

    public static String saveFile(MultipartFile file) throws IOException {
        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;

        // 保存文件
        File destFile = new File(uploadDir.getAbsolutePath() + File.separator + filename);
        file.transferTo(destFile);

        // 返回文件访问路径
        return "/uploads/images/" + filename;
    }
} 